package testappclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.*;

public class Client {
    //Порт, на котором слушает сервер
    private final int serverPort = 5555;
    //Адрес сервера
    private final String serverHost = "127.0.0.1";
    //Сокет, для подключения к серверу
    private Socket mySocket;
    //Поток ввода данных от сервера
    private BufferedReader input;
    //Статус соединения
    private boolean isConnected;
    //Примитив синхронизации
    private Lock lock;

    private boolean isStoping = false;

    //Конструктор
    public Client() throws IOException, InterruptedException {
        while (true) {
            try {
                mySocket = new Socket(serverHost, serverPort);
                break;
            } catch (IOException e) {
                Thread.sleep(100);
            }
        }
        input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
        isConnected = false;
        lock = new ReentrantLock();
    }

    //Запускает клиента
    public void Start() {
        isConnected = true;
        //Создаем и сразу запускаем клиентский поток
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (isConnected) {
                    lock.lock();
                    try {
                       while (!input.ready()) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        String line = input.readLine();
                        Main.Processing(line);
                    } catch (Exception e) {
                        Stop();
                    } finally {
                        lock.unlock();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }            
        }).start();
    }

    //Останавливает клиента
    public void Stop() {
        try {
            try {
                lock.lock();
                isConnected = false;
                try {
                Thread.sleep(0);
                } catch (InterruptedException ex) { }
            } finally {
                lock.unlock();
            }
            mySocket.close();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, "Server stop error: ", ex);
        }
    }
}
